# 学生管理系统
import os
import sys


# 记录所有的学生
students = []


def save():
    """
    用于存档
    """
    with open("students.txt", "w", encoding="utf8") as f:
        for s in students:
            f.write(f"{s['student_id']}\t{s['name']}\t{s['gender']}\t{s['class_id']}\n")
        print(f"共存档了 {len(students)} 条数据")


def load():
    """
    用于读档
    """
    # 如果文档不存在， 就直接跳过读档环节
    # 为了防止读档时文档不存在触发异常
    if not os.path.exists("students.txt"):
        return
    # 读档时, 记住将之前的内容清空
    global students
    students = []
    with open("students.txt", "r", encoding="utf8") as f:
        # 一次读取一行
        for line in f:
            # 注意这里 删除前后的多余的空格之后, 要用新的变量进行接收
            line = line.strip()
            # 根据空格对不同属性进行拆分
            tokens = line.split("\t")
            if len(tokens) != 4:
                print(f"文件格式有误, line={line}")
                continue
            student = {
                "student_id": tokens[0],
                "name": tokens[1],
                "gender": tokens[2],
                "class_id": tokens[3]
            }
            students.append(student)
        print(f"读档成功！ 共读取 {len(students)} 条数据")


def menu():
    print("1. 新增学生")
    print("2. 查看学生")
    print("3. 查找学生")
    print("4. 删除学生")
    print("0. 退出系统")
    choice = input("请输入选项: ")
    return choice


def insert():
    print("[新增学生] 开始!")
    student_id = input("请输入学生的学号: ")
    name = input("请输入学生的姓名: ")
    gender = input("请输入学生的性别: ")
    if gender not in ("男", "女"):
        print("学生性别输入不合法, 新增学生失败!")
        return
    class_id = input("请输入学生的班级:　")
    student = {
        "student_id": student_id,
        "name": name,
        "gender": gender,
        "class_id": class_id
    }
    # 放到学生列表里面
    students.append(student)
    # 存档
    save()
    print("[新增学生] 结束!")


def display():
    print("[查询学生] 开始!")
    for s in students:
        print(f"{s['student_id']}\t{s['name']}\t{s['gender']}\t{s['class_id']}\n", end="")
    print(f"共显示 {len(students)} 条数据")
    print("[查询学生] 结束!")


def find():
    print("[查找学生] 开始!")
    count = 0
    name = input("请输入要查找的学生的姓名: ")
    for student in students:
        if student["name"] == name:
            print(f"{student['student_id']}\t{student['name']}\t{student['gender']}\t{student['class_id']}")
            count += 1
    print(f"共查找到 {count} 条数据")
    print("[查找学生] 结束!")


def delete():
    print("[删除学生] 开始!")
    student_id = input("请输入要删除的学生的学号: ")
    for student in students:
        if student["student_id"] == student_id:
            print("已删除学生: ")
            print(f"{student['student_id']}\t{student['name']}\t{student['gender']}\t{student['class_id']}")
            students.remove(student)
    save()
    print("[删除学生] 结束!")


def main():
    """
    入口函数
    """
    print("--------------------------------")
    print("|       欢迎来到学生管理系统      |")
    print("--------------------------------")
    # 需要在程序启动的时候 进行读档
    load()
    while True:
        # 打印菜单选项
        choice = menu()
        if choice == '1':
            insert()
        elif choice == '2':
            display()
        elif choice == '3':
            find()
        elif choice == '4':
            delete()
        elif choice == '0':
            sys.exit(0)
        else:
            print("选项不合法, 请重新输入!")


main()